<template>
  <div>

    <div>
      <button
        type="button"
        class="btn btn-default"
        id="et"
        style="margin: 5px 0 5px 40px"
      >
        Event Type
      </button>
      <button
        type="button"
        class="btn btn-default"
        id="pm"
        style="margin: 5px 0 5px 5px"
      >
        Parameters
      </button>
      <div style="height: 40px">

      </div>
      <!-- 按钮-->
      <div class="lenged" style="display: none">
        <ul class="u"></ul>
      </div>
      <div class="event_paramet" style="display: none">
        <ul class="uu"></ul>
      </div>

      <div id="container"></div>

      <div id="footer"></div>
    </div>

  </div>
</template>

<script>
import * as echarts from "echarts";


export default {
  name:"eegshow",
  props:{
    eeg:{}
  }
,
  data() {
    return {

    };
  },
  //如果不加入watch的话会有一些问题的就是不会实时更新的，这个要注意一下的
  watch:{
    eeg(newVal,oldVal){
      //console.log("数据已更新")
      this.eeg=newVal;

      if(this.eeg.data!=null)
      {
        this.generateChartForward(this.eeg);
      }
      else{
        //console.log("数据未传递")
      }

    },

    },
    methods: {
    //localhost:9528/#/brain/eeg?path=D%3A%5Cmatlab%5Ctest%5Cexample%5CBP%5Coutput%5Ce8fajs_CompareNumber_EEG%5C1

    soloLenged(arr) {
      var res = [];
      for (var i = 0; i < arr.length; i++) {
        var repeat = true;
        for (let j = 0; j < res.length; j++) {
          if (arr[i].name == res[j].name) {
            repeat = false;
          }
        }
        if (repeat) {
          res.push(arr[i]);
        }
      }
      return res;
    },


    generateChartForward(resp) {

      var eegdata = resp.data;
      var eegdata_a = [];
      for(var i =0; i<eegdata.length;i++)
      {
        eegdata_a.push(0)
        for(var j = 0;j<eegdata[i].length;j++)
        {
          eegdata_a[i] +=eegdata[i][j];


        }
        eegdata_a[i] = eegdata_a[i]/eegdata[i].length
        for(var j = 0;j<eegdata[i].length;j++)
        {
          eegdata[i][j] =eegdata[i][j] - eegdata_a[i];


        }
      }


      var th = resp.theta;
      var rd = resp.radius;
      var event_type = resp.event_type;
      var event_latency = resp.event_latency;
      var star = resp.start;
      var end = resp.end;
      var srate = resp.srate;
      var xmin = resp.xmin;
      var xmax = resp.xmax;
      var ref = resp.ref;
      var erp = resp.erp;
      //var time = resp.time;
      var time = [];
      for (let i = 0; i <= 5 * srate; i++) {
               //time.add(star + i  / srated[0]);
        time.push(star + i/srate)
      }

      // console.log(time)

      //这里做一下erp的开始位置加工

      if(erp!=null&&erp.length!=0)
      {
        //console.log("this data is erp")
        var allLength = xmax - xmin;
        for(let i=0;i<(end - star)/allLength;i++)
        {
          event_type.push(' ')
          event_latency.push((i+star)*srate*allLength)

        }

      }










      //var time =
      var labels = resp.labels;

      var h = eegdata.length;
      var count = h / 10;
      var dom = document.getElementById("container");
      var resizeMainContainer = function () {
        dom.style.width = window.innerWidth - 240 + "px";
        dom.style.height =
          (h / Math.floor(window.innerHeight / 60)) * window.innerHeight +
          240 +
          "px";

        // dom.style.width = "100px";
        // dom.style.height = "100px";
      };
      resizeMainContainer();
      var myChart = echarts.init(dom);
      window.addEventListener("resize", function () {
        //resizeMainContainer();
        myChart.resize();
      });
      //1. ------------   图表标题
      var overViewTitle = "EEG View";

      //2. -------------   图表定位
      var chartGridTop = 100;
      var chartGridHeight = 60;

      var intervaltemp = Math.floor(time.length / 5)-1;
      // console.log(intervaltemp+"iiiiiiiiiiiiiiiiiiiiiiiii")
      // var intervaltemp = Math.floor(time.length / 5);
      var timen = [];
      for (var i = 0; i < time.length; i++) {
        timen[i] = time[i].toFixed(4);
      }

      var X = []; //用于存放电极x坐标
      var Y = []; //用于存放电极y坐标
      var shrinkScale = 80;

      if (th !== null) {
        for (var i = 0; i < th.length; i++) {
          var temp = (Math.PI / 180) * th[i];
          var y = (rd[i] * Math.cos(temp) * shrinkScale) / 0.85;
          var x = (rd[i] * Math.sin(temp) * shrinkScale) / 0.85;
          X[i] = x;
          Y[i] = y;
        }
      } else {
        var linerank = Math.ceil(labels.length / 10); // 代表一行放置8个，一共的导联数
        for (var i = linerank, g = 0; i < 0, g < labels.length; i--) {
          for (var j = 0; j < 10; j++) {
            Y[g] = i;
            g++;
          }
        }
        for (var i = 0, g = 0; i < linerank; i++) {
          for (var j = 1; j <= 10; j++) {
            X[g] = j;
            g++;
          }
        }
      }

      //------------- 事件标签event_type中 markLine的data需要数组对象
      //--------event_type的颜色数组
      var tocolor = [
        "#096",
        "#635A06",
        "#6F1861",
        "#ff9933",
        "#cc0033",
        "#660099",
        "#7e0023",
        "#6AA6AD",
        "#999999",
        "#007BBB",
      ];
      function unique(arr) {
        var newArray = [];
        for (var i = 0; i < arr.length; i++) {
          if (newArray.indexOf(arr[i]) === -1) {
            newArray.push(arr[i]);
          }
        }
        return newArray;
      }

      var newetp0 = unique(event_type);
      var uul = newetp0.length;

      var objMlData = [];

      for (var i = 0; i < event_type.length; i++) {
        var obj = {};

        var lineStyle = {};

        var rep_event_type = event_type.toString(); // 转字符串

        if (
          rep_event_type
            .substr(0, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul]) != -1
        ) {
          lineStyle.color = tocolor[0];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 1]) != -1
        ) {
          lineStyle.color = tocolor[1];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 2]) != -1
        ) {
          lineStyle.color = tocolor[2];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 3]) != -1
        ) {
          lineStyle.color = tocolor[3];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 4]) != -1
        ) {
          lineStyle.color = tocolor[4];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 5]) != -1
        ) {
          lineStyle.color = tocolor[5];
        } else if (
          rep_event_type
            .substr(1, rep_event_type.length - 1)
            .split(",")
            [i].indexOf(newetp0[uul - uul + 6]) != -1
        ) {
          lineStyle.color = tocolor[6];
        } else {
          lineStyle.color = tocolor[7];
        }

        if (event_latency[i] < star * srate || event_latency[i] > end * srate) {
          continue;
        }

        obj.name = event_type[i];
        obj.xAxis = event_latency[i] - star * srate;
        obj.lineStyle = lineStyle;

        objMlData.push(obj);
      }

      var solol = this.soloLenged(objMlData);
      var sololName = solol.map(function (obj) {
        return obj.name;
      });
      var sololC = solol.map(function (obj) {
        return obj.lineStyle.color;
      });
      var new_event_type = [];
      for (var i = 0; i < objMlData.length; i++) {
        new_event_type.push(objMlData[i].name);
      }
      var objMpData = [];
      for (var i = 0; i < new_event_type.length; i++) {
        var objMp = {};

        var textStyle = {};
        textStyle.color = "red";

        var label = {};
        var formatters = new_event_type.toString();
        if (formatters.indexOf('"') != -1) {
          label.formatter = formatters
            .substr(0, formatters.length - 1)
            .split(",")
            [i].substr(
            1,
            formatters.substr(1, formatters.length - 1).split(",")[i].length -
            2
          );
        } else {
          label.formatter = formatters.substr(0, formatters.length).split(",")[
            i
            ];
        }
        label.show = seriesLabelFlag; //显示标签标注的文本
        label.textStyle = textStyle;
        label.backgroundColor = "#fff";
        label.position = "top";
        label.rotate = 90; //标注旋转
        label.align = "left"; //标注水平对齐方式
        label.distance = -50;

        objMp.xAxis = objMlData[i].xAxis;
        objMp.y = "2%";
        objMp.label = label;

        objMpData.push(objMp);
      }

      var et = document.querySelector("#et");
      var lenged = document.querySelector(".lenged");
      var ul = document.querySelector(".u");
      et.addEventListener("click", function () {
        if (lenged.style.display == "block") {
          lenged.style.display = "none";
        } else {
          //$(".u").empty();
          ul.innerHTML="";
          lenged.style.display = "block";
          var h = sololName;
          var co = sololC;
          h.forEach(function (item) {
            var li = document.createElement("li");
            ul.appendChild(li);
            li.innerHTML =
              '<div></div><span style="font-size: 13px;">' + item + "</span>";
            li.style.display = "inline-block";
            li.style.marginTop = "5px";
          });
          co.forEach(function (it, index) {
            ul.children[index].children[0].style.background = it;
            ul.children[index].children[0].style.width = "10px";
            ul.children[index].children[0].style.height = "12px";
            ul.children[index].children[0].style.display = "inline-block";
            ul.children[index].children[0].style.marginRight = "5px";
            ul.children[index].children[0].style.marginLeft = "10px";
          });
        }
      });

      //-----------参数的获取
      var srate = srate;
      var ref = ref;
      var pmName = ["srate:", "reference:"];
      var pmV = [srate, ref];

      //-----------参数显示js
      var pm = document.querySelector("#pm");
      var event_paramet = document.querySelector(".event_paramet");
      var uu = document.querySelector(".uu");
      pm.addEventListener("click", function () {
        if (event_paramet.style.display == "block") {
          event_paramet.style.display = "none";
        } else {
          uu.innerHTML="";
          event_paramet.style.display = "block";
          var h = pmName;
          var co = pmV;
          h.forEach(function (item) {
            var li = document.createElement("li");
            uu.appendChild(li);
            li.innerHTML =
              '<strong style="margin-right:10px;margin-left:10px;font-weight:400;font-size:13px;">' +
              item +
              '</strong><span class="pmlist"></span>';
            li.style.display = "block";
          });
          co.forEach(function (it, index) {
            var spans = document.querySelectorAll(".pmlist");
            spans[index].innerHTML = it;
          });
        }
      });

      var grid = [];
      for (var i = 0; i < h; i++) {
        grid.push({
          left: 70,
          right: 60,
          top: chartGridTop + chartGridHeight * i,
          height: chartGridHeight,
        });
      }

      var xAxis = [];
      for (var i = 0; i < h; i++) {
        //避免x轴数据显示过于频繁
        var axisLabelFlag = false;
        var axisLineFlag = false;
        var axisTickFlag = false;
        var nameFlag = "";
        if (i == h - 1) {
          axisLabelFlag = true;
          axisLineFlag = true;
          axisTickFlag = true;
          nameFlag = "s";
        }
        xAxis.push({
          type: "",
          axisLine: {
            show: axisLineFlag,
            onZero: false,
          },
          name: nameFlag,
          gridIndex: i, //x轴坐标系的标号 由i代替
          //统一时间轴数据
          data: timen,
          axisLabel: {
            show: axisLabelFlag,
            showMaxLabel: true,
            interval: intervaltemp, //可以设置间隔
            formatter: function(v) {   //这里将横坐标四舍五入了
                let v1 = Number(v)
                v1.toFixed(1)
                return String(v1)
            }
          },
          axisTick: {
            show: axisTickFlag,
          },
        });
      }

      var yAxis = [];
      for (var i = 0; i < h; i++) {
        yAxis.push({
          type: "value",
          nameLocation: "middle",
          nameGap: "10",
          gridIndex: i, //y轴的标号i
          nameTextStyle: {
            padding: [4, 0, 0, 8],
            fontWeight: "bolder", //y轴名称样式
            color: "#333",
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          name: labels[i],
          nameRotate: 0,
          nameLocation: "center",
          splitNumber: 30, //调整间隔
          splitLine: {
            show: false,
          },
        });
      }

      var series = [];
      var seriesLabelFlag = null;
      for (var i = 0; i < eegdata.length; i++) {
        seriesLabelFlag = false;
        if (i == 0) {
          seriesLabelFlag = true;
        }
        series.push({
          type: "line",
          name: labels[i],
          xAxisIndex: i,
          yAxisIndex: i,
          data: eegdata[i],
          smooth: true,
          itemStyle: {
            opacity: 0, //表示不绘制折线上的点
          },
          markLine: {
            symbol: "none",
            silent: true,
            lineStyle: {
              normal: {
                type: "solid",
              },
            },
            label: {
              show: false,
              position: "end",
            },
            data: objMlData,
          },
          markPoint: {
            silent: true, //不响应和鼠标触发事件
            symbolSize: 0.1,
            data: objMpData,
          },
          color: "#2F4554", //原来颜色为#5793f3 老师说颜色有点淡   202079
        });
      }

      var indexData = [];
      for (var i = 0; i < h; i++) {
        indexData.push(i);
      }

      var option = {
        animation: false,

        //标题组件，包含主标题和副标题
        title: {
          x: "center",
          text: overViewTitle,
        },
        toolbox: {
          itemSize: 10, //工具栏icon的大小
          showTitle: true, //是否在鼠标hover的时候显示每个工具icon的标题
          right: "2%",
          itemGap: 14,
          feature: {
            restore: {},
            dataView: {},
            saveAsImage: {},
            brush: {
              show: false,
            },
          },
        },
        tooltip: {
          //移动轴展示方式
          trigger: "axis",
          triggerOn: "click", //鼠标点击时出现提示框
          transitionDuration: 0,
          showContent: true, //是否显示提示框浮
          enterable: true, //鼠标是否可进入提示框浮层中
          confine: false,
          borderWidth: 1,
          borderColor: "#fff",
          backgroundColor: "rgba(255,255,255,0)",
          textStyle: {
            fontSize: 12,
            color: "#333",
          },
          // ------- 功能是转换tooltip中显示内容，未使用异步回调，tooltip样式在外部调整
          formatter: function (obj) {
            var valueT = [];
            for (var i = 0; i < obj.length; i++) {
              if (obj[i].value != undefined) {

                valueT[obj[i].componentIndex] = obj[i].value;
              }
            }
            for (var i = 0; i < valueT.length; i++) {


              valueT[i] += eegdata_a[i];

            }
            // ------- visualMap中的最大值和最小值
            var visMin = Math.ceil(Math.min.apply(null, valueT));
            var visMax = Math.floor(Math.max.apply(null, valueT));

            var timeClick = obj[0].name;

            var value = obj.value;

            var yindex = obj.dataIndex;
            var xindex = obj.seriesIndex;
            setTimeout(function () {
              stockGraphManagement("ebox", valueT, timeClick, visMin, visMax);
              //graphChartsFn(xindex, yindex, valueT);
            }, 1000);
            return '<div style="width:380px;height:300px;" id="ebox"></div>';
          },
        },

        //实现选框
        brush: {
          seriesIndex: "all",
          xAxisIndex: "all",
          yAxisIndex: "all",
          brushType: "rect",
          brushMode: "multiple",
          transformable: false,
          brushStyle: {
            borderWidth: 1,
            color: "rgba(00,80,00,0.3)",
            borderColor: "rgba(00,80,00)",
          },
        },

        axisPointer: {
          type: "line",
          link: {
            xAxisIndex: "all",
          },
          linkStyle: {
            color: "#0000",
            width: 10,
          },
        },

        grid: grid,

        xAxis: xAxis,

        yAxis: yAxis,

        // graphic: [
        //   {
        //     type: "text",
        //     left: window.innerWidth - 300,
        //     bottom: 180,
        //     style: {
        //       text: "scale",
        //       textAlign: "center",
        //       fill: "#333",
        //     },
        //   },
        // ],

        dataZoom: [
          {
            type: "slider",
            top: chartGridTop + chartGridHeight * h + 40,
            xAxisIndex: indexData,
            realtime: true,
            //移动端展示方式
            handleSize: "140%",
          },
          // {
          //   type: "slider",
          //   show: true,
          //   yAxisIndex: indexData,
          //   filterMode: "empty",
          //   width: 2,
          //   borderColor: "#2F4554",
          //   backgroundColor: "#2F4554",
          //   height: "1%",
          //   showDataShadow: false, //dataZoom-slider组件中显示数据阴影 反应数据走势
          //   left: "97%",
          //   bottom: "5%",
          //   realtime: true,
          //   //移动端展示方式
          //   handleSize: "140%",
          // },
        ],

        series: series,
      };

      if (option && typeof option === "object") {
        myChart.setOption(option, true);
      }

      function stockGraphManagement(odiv, valueT, timeClick, visMin, visMax) {
        var topo = [];
        for (var i = 0; i < X.length; i++) {
          var temp1 = {};
          temp1.name = labels[i];
          temp1.value = [X[i], Y[i], valueT[i]];
          topo[i] = temp1;
        }
        var myChartToolgraph = echarts.init(document.getElementById(odiv));

        var myChartTool = {
          title: {
            x: "center",
            text: "Topo",
            subtext: "Time:" + timeClick + "s", //副标题时间
            subtextStyle: {
              align: "left",
              color: "red"
            },
          },
          tooltip: {
            show: true,
            formatter: function (obj) {
              return obj.name + " : " + obj.value[2].toFixed(2);
            },
          },
          xAxis: {
            type: "value",
            show: false,
          },
          yAxis: {
            type: "value",
            show: false,
          },
          animationDurationUpdate: 1500,
          animationEasingUpdate: "quinticInOut",
          //连续型视图映射组件
          visualMap: {
            type: "continuous",
            min: visMin,
            max: visMax,
            calculable: true,
            dimension: 2,
            hoverLink: true,
            itemWidth: 10,
            itemHeight: 70,
            inRange: {
              color: [
                //'#d94e5d','#eac736','#50a3ba'.reverse(),
                "#f2c31a",
                "#24b7f2",
              ].reverse(),
            },
            right: 0,
          },
          series: [
            {
              type: "scatter",
              coordinateSystem: "cartesian2d",
              layout: "none",
              symbol: "circle",
              symbolSize: 20,
              roam: true,
              itemStyle: {
                opacity: 1,
              },
              label: {
                show: true,
              },
              edgeSymbol: ["circle", "arrow"], //关系图样式
              edgeSymbolSize: [4, 10],
              edgeLabel: {
                fontSize: 20,
              },
              label: {
                normal: {
                  show: true,
                  formatter: "{b}",
                  color: "#fff",
                },
              },
              data: topo,
            },
          ],
        };
        myChartToolgraph.setOption(myChartTool);
      }

      function graphChartsFn(xindex, yindex, valueT) {

        var graphdata = [valueT];
        myChartToolgraph.setOption({
          series: [
            {
              data: graphdata[xindex][yindex],
            },
          ],
        });
      }
    },



  },

};
</script>
